package com.pkx.cloud.fse7.dms.monitoring.service.impl;

import com.pkx.cloud.fse7.conf.RedisUtils;
import com.pkx.cloud.fse7.conf.StatusEnum;
import com.pkx.cloud.fse7.dms.monitoring.entity.RemoteOrder;
import com.pkx.cloud.fse7.dms.monitoring.feign.RemoteOrderFeign;
import com.pkx.cloud.fse7.dms.monitoring.service.RemoteOrderService;
import com.pkx.cloud.fse7.dms.monitoring.service.StatusService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Description
 * @Author chenwg
 * @date 2020.12.24 18:46
 */
@Service
@Slf4j
public class RemoteOrderServiceImpl implements RemoteOrderService {
    @Resource
    private RemoteOrderFeign remoteOrderFeign;
    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private StatusService statusService;

    @Override
    @Async
    public String open(RemoteOrder remoteOrder) {
        // 加入分布式锁 1秒只能调用一次
        String key = String.valueOf(remoteOrder.getOrder());
        boolean result = redisUtils.tryLock(key, "1", 3L);
        while (!result) {
            result = redisUtils.tryLock(key, "1", 3L);
            log.info("锁状态{}", result);
        }
        log.info("锁获取成功{}", result);
        String open = remoteOrderFeign.open(remoteOrder);
        // 释放锁
        redisUtils.unLock(key, "1");
        String devId = remoteOrder.getDevId();
        String parameter = remoteOrder.getParameter();
        int order = remoteOrder.getOrder();
        // 5 常开 6 常闭 7正常
        if (order == StatusEnum.open.getCode() || order == StatusEnum.close.getCode() || order == StatusEnum.normal.getCode()) {
            statusService.addStatus(devId.concat(":").concat(parameter), order);
        }
        return open;
    }
}
